package com.yxkj.syh.app.huarong.activities.creat;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.lcw.library.imagepicker.ImagePicker;
import com.syh.app.basic.base.BaseActivity;
import com.syh.app.basic.bean.LiveDataEvent;
import com.syh.app.basic.config.BasicConstants;
import com.syh.app.basic.utils.AppUtil;
import com.syh.app.basic.utils.ComUtil;
import com.syh.app.basic.utils.PermissionUtil;
import com.syh.app.basic.utils.Tooast;
import com.syh.app.basic.utils.imagepickerhelper.ImagePickerHelper;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yxkj.syh.app.huarong.BR;
import com.yxkj.syh.app.huarong.R;
import com.yxkj.syh.app.huarong.activities.creat.add_goods.AddGoodsActivity;
import com.yxkj.syh.app.huarong.activities.item_select.AddressSelectActivity;
import com.yxkj.syh.app.huarong.adps.AddedGoodsAdp;
import com.yxkj.syh.app.huarong.bean.Goods;
import com.yxkj.syh.app.huarong.bean.PaperFactory;
import com.yxkj.syh.app.huarong.constants.ArouterPath;
import com.yxkj.syh.app.huarong.databinding.ActivityNewOutOrderBinding;
import com.yxkj.syh.app.huarong.util.PhotoUtil;
import com.yxkj.syh.app.huarong.views.AddressDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 外调订单
 */
@Route(path = ArouterPath.NEW_OUT_ORDER_ACTIVITY)
public class NewOutOrderActivity extends BaseActivity<ActivityNewOutOrderBinding, NewOutOrderVM> {

    private static final int PERMISSION_IMAGE = 0xb12;

    AddedGoodsAdp mAddedGoodsAdp;
    private AddressDialog addressDialog;
    private int mCarType = 0;//0  车头   1 挂车
    private int areaType = 0;//发 与 终       0 发  1  终

    @Override
    protected int getContentLayout() {
        return R.layout.activity_new_out_order;
    }

    @Override
    protected int getViewModelId() {
        return BR.newOutOrderVM;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        mVDBinding.titleView.setLeftOnClickListener(v -> {
            finish();
        });

        mVDBinding.tvAddGoods.setOnClickListener(v -> {
            addGoods(null);
        });

        mAddedGoodsAdp = new AddedGoodsAdp();
        mAddedGoodsAdp.setOnClick(goods -> {
            addGoods(goods);
        });
        mVDBinding.rvGoods.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        mVDBinding.rvGoods.setAdapter(mAddedGoodsAdp);
        mViewModel.setAddedGoodsAdp(mAddedGoodsAdp);

        mVDBinding.llFromArea.setOnClickListener(v -> {
            areaType = 0;
            selectArea();
        });
        mVDBinding.etFromArea.setOnClickListener(v -> {
            areaType = 0;
            selectArea();
        });
        mVDBinding.llToArea.setOnClickListener(v -> {
            areaType = 1;
            selectArea();
        });
        mVDBinding.etToArea.setOnClickListener(v -> {
            areaType = 1;
            selectArea();
        });
        mVDBinding.tvUsedFrom.setOnClickListener(v -> {
            Intent intent = new Intent(NewOutOrderActivity.this, AddressSelectActivity.class);
            startActivityForResult(intent, 0x1a);
        });
        mVDBinding.tvUsedTo.setOnClickListener(v -> {
            Intent intent = new Intent(NewOutOrderActivity.this, AddressSelectActivity.class);
            startActivityForResult(intent, 0x2a);
        });
        mVDBinding.ivCarTrailerNo.setOnClickListener(v -> {
            mCarType = 1;
            AndPermission.with(NewOutOrderActivity.this).requestCode(PERMISSION_IMAGE)
                    .permission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .callback(mPermissionListener).start();
        });
        mVDBinding.ivCarHeadNo.setOnClickListener(v -> {
            mCarType = 0;
            AndPermission.with(NewOutOrderActivity.this).requestCode(PERMISSION_IMAGE)
                    .permission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .callback(mPermissionListener).start();
        });
    }

    @Override
    protected void initData() {
        mViewModel.getOrderInfo().setLineType(0);
    }

    @Override
    protected void initObservers() {
        super.initObservers();
        mViewModel.mldCreatedSuccess.observe(this, orderInfo -> {
            new AlertDialog.Builder(NewOutOrderActivity.this).setMessage("是否立即发车？").setCancelable(false)
                    .setNegativeButton("暂不发车", (dialog, which) -> {
                        EventBus.getDefault().post(new LiveDataEvent(BasicConstants.EVENT_SELECT_ORDER_ALL));
                        dialog.cancel();
                        finish();
                    }).setPositiveButton("立即发车", (dialog, which) -> {
                dialog.cancel();
                EventBus.getDefault().post(new LiveDataEvent(BasicConstants.EVENT_SELECT_ORDER_ALL));
                ARouter.getInstance().build(ArouterPath.EDIT_ORDER_ACTIVITY).withSerializable("orderInfo", orderInfo).navigation();
                finish();
            }).create().show();
        });

    }

    private void addGoods(Goods clickedGoods) {

        ArrayList<String> added = new ArrayList<>();
        for (Goods goods : mAddedGoodsAdp.getData()) {
            String tag = goods.getCode();
            added.add(tag);
        }
        Intent intent = new Intent(NewOutOrderActivity.this, AddGoodsActivity.class);
        intent.putStringArrayListExtra("added", added);
        if (clickedGoods != null) {
            intent.putExtra("preSelectedGoods", clickedGoods);
        }
        startActivityForResult(intent, 0x4a);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0x4a) {
                Goods goods = (Goods) data.getSerializableExtra("goods");
                int operate = data.getIntExtra("operate", -1);
                if (operate == 0) {//添加
                    mAddedGoodsAdp.add(goods);
                } else if (operate == 1) {//移除
                    mAddedGoodsAdp.remove(goods);
                } else if (operate == 2) {//编辑
                    mAddedGoodsAdp.change(goods);
                }
            } else if (requestCode == 0x1a) {
                PaperFactory factory = (PaperFactory) data.getSerializableExtra("data");
                mViewModel.ofFromArea.set(factory.getArea().replace("/", ""));
                mViewModel.ofFromAddress.set(factory.getAddress());
                mViewModel.getOrderInfo().setStartArea(factory.getArea());
                mViewModel.getOrderInfo().setStartAreaIds(factory.getAreaIds());
            } else if (requestCode == 0x2a) {
                PaperFactory factory = (PaperFactory) data.getSerializableExtra("data");
                mViewModel.ofToArea.set(factory.getArea().replace("/", ""));
                mViewModel.ofToAddress.set(factory.getAddress());
                mViewModel.getOrderInfo().setEndArea(factory.getArea());
                mViewModel.getOrderInfo().setEndAreaIds(factory.getAreaIds());

            } else if (requestCode == ImagePickerHelper.REQUEST_SELECT_IMAGES_CODE) {
                List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
                Luban.with(this).load(imagePaths.get(0))
                        .setTargetDir(AppUtil.getLubanPath())
                        .ignoreBy(100)
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                showLoading("Compress");
                            }

                            @Override
                            public void onSuccess(File file) {
                                hideLoading("Compress");
                                mViewModel.scanCarId(file.getPath(), mCarType);
                            }

                            @Override
                            public void onError(Throwable e) {
                                hideLoading("Compress");
                                Tooast.normalInfo("压缩图片错误");

                            }
                        }).launch();
            } else if (requestCode == PhotoUtil.GET_IMAGE_BY_CAMERA) {
                File imageFile;
                if (Build.VERSION.SDK_INT >= 19) {
                    imageFile = ComUtil.getUriFromKitKat(this, PhotoUtil.imageUriFromCamera);
                } else {
                    imageFile = ComUtil.getUriBeforeKitKat(this, PhotoUtil.imageUriFromCamera);
                }
                if (imageFile.length() > 2 * 1024 * 1024) {
                    Luban.with(this).load(imageFile)
                            .setTargetDir(AppUtil.getLubanPath())
                            .ignoreBy(100)
                            .setCompressListener(new OnCompressListener() {
                                @Override
                                public void onStart() {
                                    showLoading("Compress");
                                }

                                @Override
                                public void onSuccess(File file) {
                                    hideLoading("Compress");
                                    mViewModel.scanCarId(file.getPath(), mCarType);
                                }

                                @Override
                                public void onError(Throwable e) {
                                    hideLoading("Compress");
                                    Tooast.normalInfo("压缩图片错误");

                                }
                            }).launch();
                } else {
                    mViewModel.scanCarId(imageFile.getPath(), mCarType);
                }
            }
        }
    }


    /**
     * 选择地区
     */
    private void selectArea() {//0 发  1  终
        if (addressDialog == null) {
            addressDialog = new AddressDialog(NewOutOrderActivity.this);
            addressDialog.setOnAddressSelectedListener((province, city, county, street) -> {
                addressDialog.cancel();
                StringBuffer bufferName = new StringBuffer();
                StringBuffer bufferCode = new StringBuffer();
                bufferName.append(province.name);
                bufferCode.append(mViewModel.getAreaPlusId(1, province.id));
                if (city != null) {
                    bufferCode.append(",").append(mViewModel.getAreaPlusId(2, city.id));
                    bufferName.append("/").append(city.name);
                    if (county != null) {
                        bufferCode.append(",").append(mViewModel.getAreaPlusId(3, county.id));
                        bufferName.append("/").append(county.name);
                    }
                }
                if (areaType == 0) {
                    mViewModel.ofFromArea.set(bufferName.toString().replace("/", ""));
                    mViewModel.getOrderInfo().setStartArea(bufferName.toString());
                    mViewModel.getOrderInfo().setStartAreaIds(bufferCode.toString());
                } else if (areaType == 1) {
                    mViewModel.ofToArea.set(bufferName.toString().replace("/", ""));
                    mViewModel.getOrderInfo().setEndArea(bufferName.toString());
                    mViewModel.getOrderInfo().setEndAreaIds(bufferCode.toString());
                }
            });
            addressDialog.getSelector().setAddressProvider(mViewModel.addressProvider);
        }
        addressDialog.show();
    }


    private void startImageLib() {
        ImagePickerHelper.startImagePicker(this);
    }

    private PermissionListener mPermissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == PERMISSION_IMAGE) {
                new AlertDialog.Builder(NewOutOrderActivity.this).setItems(new String[]{"相册", "拍照"}, (dialog, which) -> {
                            dialog.cancel();
                            if (which == 0) {
                                startImageLib();
                            } else if (which == 1) {
                                PhotoUtil.openCameraImage(NewOutOrderActivity.this);
                            }
                        }
                ).create().show();
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == PERMISSION_IMAGE) {
                PermissionUtil.with(NewOutOrderActivity.this)
                        .addPermission(Manifest.permission.CAMERA)
                        .addPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                        .addPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .initPermission();
            }
        }
    };


}
